package com.banciyuan.bcywebview.biz.detail.mixweb;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.comment.CommentConstants;
import com.banciyuan.bcywebview.biz.detail.comment.CommentHelper;
import com.banciyuan.bcywebview.biz.detail.comment.IGetComment;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailType;


public class MixWebCommentActivity extends BaseActivity implements View.OnClickListener, BaseWatcher {

    private PullToRefreashRecycleView mRefreshListView;
    private RecyclerView mListView;
    private TextView tvTotolCounts;
    private List<DetailComment> mReplyCommentList = new ArrayList<>();
    private int page = 1;
    private int count;
    private String uid;

    private MixWebCommentAdapter mDetailCommentAdapter;
    private DetailType mDetailType;
    private boolean loading = false;
    private boolean end_flag = false;
    private ProgressbarHelper mProgressbarHelper;
    private CommentHelper commentHelper;
    private boolean showEdit;
    private String comment_guide;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_recycleview_pull);
        initArgs();
        initActionbar();
        initUi();
        initProgressbar();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        uid = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        mDetailType = (DetailType) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_TWO);
        count = intent.getIntExtra(gotoUtil.INTENT_VALUE_THREE, 0);
        showEdit = intent.getBooleanExtra(gotoUtil.INTENT_VALUE_FOUR, false);
        comment_guide = intent.getStringExtra(CommentConstants.COMMENT_HINT);
        commentHelper = new CommentHelper(this, mDetailType);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    mProgressbarHelper.onLoading();
                    loading = true;
                    end_flag = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        tvTotolCounts = ((TextView) findViewById(R.id.base_action_bar_title));
        findViewById(R.id.base_action_bar_home).setOnClickListener(this);
    }

    @Override
    protected void initUi() {
        mRefreshListView = (PullToRefreashRecycleView) findViewById(R.id.listView);
        mListView = mRefreshListView.getRefreshableView();
        mListView.setLayoutManager(new LinearLayoutManager(this));

        tvTotolCounts.setText(String.format(getString(R.string.comment_count_format), count));
        RecyclerView.ItemAnimator animator = mListView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        ((TextView) findViewById(R.id.reply_btn)).setText(TextUtils.isEmpty(comment_guide) ? getString(R.string.want_comment) : comment_guide);
    }

    @Override
    protected void initAction() {
        findViewById(R.id.rl_publish).setOnClickListener(this);
        mListView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });

        mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                loading = false;
                end_flag = false;
                page = 1;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        commentHelper.getCommentData(page, new IGetComment() {
            @Override
            public void getSucc(String json) {
                if (StatusCodeUtils.dealStatusCode(json, MixWebCommentActivity.this)) {
                    try {
                        Gson gson = new Gson();
                        List<DetailComment> templist = gson.fromJson(new JSONObject(json).getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DetailComment>>() {
                        }.getType());
                        if (templist.isEmpty()) {
                            end_flag = true;
                        }
                        processCommentsData(templist);
                        processShowEditData();
                        onSuccess();
                    } catch (Exception e) {
                        onError();
                    }
                } else {
                    onError();
                }
            }

            @Override
            public void getFail() {
                onError();
            }
        });
    }

    private void processShowEditData() {
        if (showEdit) {
            showEdit = false;
            doReply();
        }
    }

    private void onSuccess() {
        mProgressbarHelper.onSuccess();
        mRefreshListView.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        tvTotolCounts.setText(String.format(getString(R.string.reply_count_format), 0));
        mProgressbarHelper.onFailed();
        mRefreshListView.onRefreshComplete();
        loading = false;
    }

    private void processCommentsData(List<DetailComment> templist) {
        CommentHelper.processTemList(templist);
        if (page == 1) {
            mReplyCommentList.clear();
        }
        mReplyCommentList.addAll(templist);
        if (mDetailCommentAdapter == null) {
            mDetailCommentAdapter = new MixWebCommentAdapter(this, mReplyCommentList, uid, mDetailType);
            mListView.setAdapter(mDetailCommentAdapter);
        } else {
            mDetailCommentAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_publish:
            case R.id.iv_sofa:
                doReply();
                break;
            case R.id.base_action_bar_home:
                finish();
                break;
        }
    }

    public void doReply() {
        Intent intent = new Intent(this, EditActivity.class);
        intent.putExtra(CommentConstants.SHOW_CHARGE, false);
        intent.putExtra(CommentConstants.COMMENT_HINT, comment_guide);
        DetailDataHelper.putBaseDetailValue(intent, mDetailType);
        startActivityForResult(intent, CommentConstants.GO_COMMENT);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommentConstants.GO_REPLY && resultCode == EditActivity.END_ADD) {
            count = count + 1;
            dealAddReply(data);
        } else if (requestCode == CommentConstants.GO_COMMENT && resultCode == EditActivity.END_ADD) {
            count = count + 1;
            dealAddComment(data);
        }
    }

    private void dealAddReply(Intent data) {
        DetailComment replyDetail = (DetailComment) data.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        int pos = data.getIntExtra(gotoUtil.INTENT_VALUE_TWO, -1);
        if (null != mDetailCommentAdapter) {
            if (pos != -1) {
                DetailComment commentDetail = mReplyCommentList.get(pos);
                int commentCount = commentDetail.getComments_count() + 1;
                commentDetail.setComments_count(commentCount);
                List<DetailComment> comments = commentDetail.getComments();
                if (null == comments) {
                    comments = new ArrayList<>();
                    commentDetail.setComments(comments);
                }
                comments.add(0, replyDetail);
            }
            mDetailCommentAdapter.notifyItemChanged(pos);
        }
        tvTotolCounts.setText(String.format(getString(R.string.comment_count_format), count));
    }

    private void dealAddComment(Intent data) {
        DetailComment detailComment = (DetailComment) data.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        mReplyCommentList.add(0, detailComment);
        if (null != mDetailCommentAdapter) {
            mDetailCommentAdapter.notifyItemInserted(0);
            mDetailCommentAdapter.notifyItemRangeChanged(0, mReplyCommentList.size());
            mDetailCommentAdapter.notifyItemChanged(mReplyCommentList.size());
        }
        tvTotolCounts.setText(String.format(getString(R.string.comment_count_format), count));
    }

    private void deleteComment(int position) {
        if (mReplyCommentList != null && position < mReplyCommentList.size()) {
            DetailComment deleteComment = mReplyCommentList.remove(position);
            int deleteNum = 1 + deleteComment.getComments_count();
            count = count - deleteNum;
            count = count < 0 ? 0 : count;
            if (mDetailCommentAdapter != null) {
                mDetailCommentAdapter.notifyItemRemoved(position);
                mDetailCommentAdapter.notifyItemRangeChanged(position, mReplyCommentList.size());
                mDetailCommentAdapter.notifyItemChanged(mReplyCommentList.size());
            }
        }
        tvTotolCounts.setText(String.format(getString(R.string.comment_count_format), count));
    }

    private void disLikeComment(int position) {
        if (mReplyCommentList != null && position < mReplyCommentList.size()) {
            DetailComment detailComment = mReplyCommentList.get(position);
            detailComment.setHave_ding(false);
            detailComment.setDing_num(detailComment.getDing_num() - 1);
            if (mDetailCommentAdapter != null) {
                mDetailCommentAdapter.notifyItemChanged(position);
            }
        }
    }

    private void LikeComment(int position) {
        if (mReplyCommentList != null && position < mReplyCommentList.size()) {
            DetailComment detailComment = mReplyCommentList.get(position);
            detailComment.setHave_ding(true);
            detailComment.setDing_num(detailComment.getDing_num() + 1);
            if (mDetailCommentAdapter != null) {
                mDetailCommentAdapter.notifyItemChanged(position);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(ComplexDetailActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(ComplexDetailActivity.class);
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.DELELE_COMMENT_EVENT:
                deleteComment((Integer) object);
                break;
            case BaseObserver.LIKE_COMMENT_EVENT:
                LikeComment((Integer) object);
                break;
            case BaseObserver.DISLIKE_COMMENT_EVENT:
                disLikeComment((Integer) object);
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
